// stock.js
const { DataTypes } = require("sequelize");
const sequelize = require("./db");
const User = require("./User");
const Merchandise = require("./Merchandise");

const Stock = sequelize.define(
  "Stock",
  {
    id: {
      type: DataTypes.BIGINT,
      autoIncrement: true,
      primaryKey: true,
    },
    // 所属用户id
    userId: {
      type: DataTypes.STRING(50),
      allowNull: false,
      references: {
        model: User, // 关联的模型
        key: 'id', // 关联的字段
      },
    },
    merchandiseId: {
      type: DataTypes.BIGINT,
      allowNull: false,
      references: {
        model: Merchandise,
        key: 'id',
      },
      onDelete: 'CASCADE', // 当商品删除时，库存记录也会被删除
    },
    quantity: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
    },
  },
  {
    paranoid: true, // 删除时间开启
  }
);

// 定义外键关系
Merchandise.hasOne(Stock, {
  foreignKey: 'merchandiseId',
  as: 'stock',
});

User.hasMany(Stock, {
  foreignKey: 'userId',
  as: 'stocks',
});

Stock.belongsTo(Merchandise, {
  foreignKey: 'merchandiseId',
  as: 'merchandise',
});

Stock.belongsTo(User, {
  foreignKey: 'userId',
  as: 'user',
});

module.exports = Stock;